<template>
  <div class="container">
    <el-form inline>
      <!-- 用户名称 -->
      <el-form-item label="用户名称">
        <el-input v-model="searchQuery.username" placeholder="请输入用户名称" clearable></el-input>
      </el-form-item>

      <!-- 手机号码 -->
      <el-form-item label="手机号码">
        <el-input v-model="searchQuery.phone" placeholder="请输入手机号码" clearable></el-input>
      </el-form-item>

      <!-- 搜索和重置按钮 -->
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
        <el-button type="info" :icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="filteredUsers" stripe @selection-change="handleSelectionChange">
      <el-table-column prop="username" label="用户名称"></el-table-column>
      <el-table-column prop="enterprise" label="公司"></el-table-column>
      <el-table-column prop="department" label="部门"></el-table-column>
      <el-table-column prop="phone" label="手机号码"></el-table-column>
      <el-table-column prop="role" label="角色名称"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button size="mini" @click="showEditUserForm(scope.row)" v-if="scope.row.role !== '超级管理员'">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination-fixed"
      layout="prev, pager, next, jumper"
      :total="totalItems"
      :page-size="pageSize"
      :current-page.sync="currentPage"
      @current-change="fetchData">
    </el-pagination>

    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="showEditUser" title="修改用户" width="30%" :style="{ maxHeight: '70vh' }">
      <el-form :model="currentUser" ref="currentUserForm" label-width="100px">
        <el-form-item label="用户名称">
          <el-input v-model="currentUser.username" readonly style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="公司">
          <el-input v-model="currentUser.enterprise" readonly style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="currentUser.department" readonly style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="currentUser.phone" readonly style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-select v-model="currentUser.role" style="width: 300px;">
            <el-option label="普通用户" value="普通用户"></el-option>
            <el-option label="企业管理员" value="企业管理员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditUser = false">取消</el-button>
        <el-button type="primary" @click="editUser">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改错误弹窗 -->
    <el-dialog v-model="EditWrongDialogVisible" title="错误" width="400px" align-center>
      <span>修改失败：用户名称、昵称、密码不能为空</span>
    </el-dialog>

    <!-- 创建错误弹窗 -->
    <el-dialog v-model="centerDialogVisible" title="错误" width="400px" align-center>
      <span>创建失败：用户名称、昵称、密码不能为空</span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  import { Search, Refresh } from '@element-plus/icons-vue';

  interface User {
    user_id: number;
    username: string;
    enterprise: string;
    department: string;
    phone: string;
    role: string;
  }

  const users = ref<User[]>([]);
  const searchQuery = reactive({
    username: '',
    phone: ''
  });

  const currentPage = ref(1);
  const totalItems = ref(0);
  const pageSize = ref(10);
  const showEditUser = ref(false);
  const EditWrongDialogVisible = ref(false);
  const centerDialogVisible = ref(false);

  const currentUser = reactive<User>({
    user_id: 0,
    username: '',
    enterprise: '',
    department: '',
    phone: '',
    role: ''
  });


  const fetchData = async (page = 1) => {
    try {
      const params: any = { page, pageSize: pageSize.value };
      const role = localStorage.getItem('role');
      
      if (role !== '超级管理员') {
        params.enterprise = localStorage.getItem('enterprise');
      }

      const response = await axios.get('http://localhost:1111/role/rolelist', { params });
      console.log(response.data);

      if (response.data.users && response.data.users.length > 0) {
        users.value = response.data.users;
        currentPage.value = response.data.currentPage;
        totalItems.value = response.data.totalItems;
      } else {
        users.value = [];
        totalItems.value = 0;
      }
    } catch (error) {
      console.error('获取数据时出错!', error);
    }
  };

  const search = async () => {
    if (searchQuery.username.trim() === '' && searchQuery.phone.trim() === '') {
      ElMessage({
        message: '请输入查询条件',
        type: 'warning',
        duration: 2000
      });
      return;
    }

    const params: any = {
      username: searchQuery.username,
      phone: searchQuery.phone
    };

    try {
      const response = await axios.get('http://localhost:1111/role/rolelist', { params });
      users.value = response.data.users;
      currentPage.value = 1;
      totalItems.value = response.data.totalItems;
    } catch (error) {
      console.error('查询时出错!', error);
    }
  };

  const reset = () => {
    searchQuery.username = '';
    searchQuery.phone = '';
    fetchData();
  };

  const filteredUsers = computed(() => {
    let filtered = users.value;

    if (searchQuery.username) {
      filtered = filtered.filter(user => user.username.includes(searchQuery.username));
    }

    if (searchQuery.phone) {
      filtered = filtered.filter(user => user.phone.includes(searchQuery.phone));
    }

    return filtered;
  });

  const showEditUserForm = (user: User) => {
    Object.assign(currentUser, user);
    showEditUser.value = true;
  };

  const editUser = async () => {
  if (!currentUser.username || !currentUser.role) {
    EditWrongDialogVisible.value = true;
    return;
  }

  try {
    const data = {
      user_id:'',
      username: currentUser.username,
      password:'',
      phone:'',
      email:'',
      sex:'',
      status:'',
      role: currentUser.role,
      nick_name:'',
      enterprise:'',
      department:'',
      userCreate:''
    };

    await axios.put('http://localhost:1111/role/update', data);
    showEditUser.value = false;
    fetchData(currentPage.value);
  } catch (error) {
    console.error('修改用户信息时出错!', error);
  }
};


  onMounted(() => {
    fetchData();
  });
</script>

<style scoped>
.container {
  width: 100%;
  text-align: left;
}

.pagination-fixed {
  position: sticky;
  bottom: 0;
  background-color: #fff;
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-dialog {
  overflow-y: auto;
}
</style>
